"""
用户管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.extensions import db
from app.models import User, Role

users_bp = Blueprint('users', __name__, url_prefix='/api/users')


@users_bp.route('', methods=['GET'])
@jwt_required()
def get_users():
    """获取用户列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        
        query = User.query
        
        if search:
            query = query.filter(
                (User.username.contains(search)) | 
                (User.email.contains(search))
            )
        
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        users = [user.to_dict() for user in pagination.items]
        
        return jsonify({
            'users': users,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取用户列表失败: {str(e)}'}), 500


@users_bp.route('', methods=['POST'])
@jwt_required()
def create_user():
    """创建用户"""
    try:
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        role_id = data.get('role_id')
        
        if not username or not email or not password:
            return jsonify({'message': '用户名、邮箱和密码不能为空'}), 400
        
        # 检查用户是否已存在
        if User.query.filter_by(username=username).first():
            return jsonify({'message': '用户名已存在'}), 400
        
        if User.query.filter_by(email=email).first():
            return jsonify({'message': '邮箱已存在'}), 400
        
        # 验证角色
        if role_id and not Role.query.get(role_id):
            return jsonify({'message': '角色不存在'}), 400
        
        user = User(
            username=username,
            email=email,
            role_id=role_id,
            is_active=data.get('is_active', True)
        )
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        return jsonify({
            'message': '用户创建成功',
            'user': user.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建用户失败: {str(e)}'}), 500


@users_bp.route('/<int:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    """更新用户"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'message': '用户不存在'}), 404
        
        data = request.get_json()
        
        # 更新用户名
        if 'username' in data:
            if data['username'] != user.username:
                if User.query.filter_by(username=data['username']).first():
                    return jsonify({'message': '用户名已存在'}), 400
                user.username = data['username']
        
        # 更新邮箱
        if 'email' in data:
            if data['email'] != user.email:
                if User.query.filter_by(email=data['email']).first():
                    return jsonify({'message': '邮箱已存在'}), 400
                user.email = data['email']
        
        # 更新密码
        if 'password' in data and data['password']:
            user.set_password(data['password'])
        
        # 更新角色
        if 'role_id' in data:
            if data['role_id'] and not Role.query.get(data['role_id']):
                return jsonify({'message': '角色不存在'}), 400
            user.role_id = data['role_id']
        
        # 更新状态
        if 'is_active' in data:
            user.is_active = data['is_active']
        
        db.session.commit()
        
        return jsonify({
            'message': '用户更新成功',
            'user': user.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新用户失败: {str(e)}'}), 500


@users_bp.route('/<int:user_id>', methods=['DELETE'])
@jwt_required()
def delete_user(user_id):
    """删除用户"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # 不能删除自己
        if current_user_id == user_id:
            return jsonify({'message': '不能删除自己的账户'}), 400
        
        user = User.query.get(user_id)
        if not user:
            return jsonify({'message': '用户不存在'}), 404
        
        db.session.delete(user)
        db.session.commit()
        
        return jsonify({'message': '用户删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除用户失败: {str(e)}'}), 500